package com.draw.server.service;

import java.util.ArrayList;
import java.util.List;

import javax.jws.WebService;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.draw.core.Word;
import com.draw.server.hibernate.HibernateUtil;
import com.draw.webinterface.WordInterface;

@WebService(targetNamespace = "http://draw.some.com/", serviceName = "WordService", name = "WordService")
public class WordService implements WordInterface {
	private static final Logger logger = LoggerFactory.getLogger(WordService.class);

	/*@Override
	public Word getRandomByLevel(Integer level) {
		Session session = HibernateUtil.getSession();
		String req = "from com.draw.core.Word where level = :level";
		Query query = session.createQuery(req);
		query.setInteger("level", level);
		List<Word> lw = extractedWords(query);
		Random rd = new Random();
		return (Word) lw.get(rd.nextInt(lw.size()));
	}*/
	//SELECT quote FROM quotes LIMIT $generated_number, 1
	

	/*public Word getRandomByLevel(Integer level) {
		Session session = HibernateUtil.getSession();
		String req = "from com.draw.core.Word where level = :level ORDER BY RAND()";
		Query query = session.createQuery(req);
		query.setInteger("level", level);
		query.setMaxResults(1);
		List l = query.list();
		if(l.isEmpty())
		{
			return new Word();
		}
		else
		{
			return (Word) query.list().get(0);
		}
		//TODO : gerer le cas ou aucun mot n'est disponibe !!
	}*/
	
	/*public Word getRandomByLevel(Integer level) {
		Session session = HibernateUtil.getSession();
		String req = "from com.draw.core.Word where level = :level";
		Query query = session.createQuery(req);
		query.setInteger("level", level);
		List<Word> lw = extractedWords(query);
		Random rd = new Random();
		return (Word) lw.get(rd.nextInt(lw.size()));
	}*/
	
	// version optimisee à tester
	@Override
	public Word getRandomByLevel(Integer level)
	{
		Session session = HibernateUtil.getSession();
		Word res =( (Word) session.createQuery("select word from Word word where level = "+level.intValue()+" ORDER BY RAND()").iterate().next() );
		return 	res;
	}

	private List<Word> extractedWords(Query query) {
		ArrayList<Word> data = new ArrayList<Word>();
		for (Object obj : query.list() ) {
			data.add((Word)obj);
		}
		return data;
	}

	@Override
	public List<Word> getAll() {
		Session session = HibernateUtil.getSession();
		String req = "from com.draw.core.Word";
		Query query = session.createQuery(req);
		return extractedWords(query);
	}

	@Override
	public Word addWord(Word word) {
		logger.info("Creating WORD : {}", word);
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		session.save(word);
		tx.commit();
		return word;
	}

}
